package com.cci.kangdao.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.cci.kangdao.dao.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.model.CompanyT;
import com.cci.kangdao.dao.model.EngineMsg;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.service.EngineMsgService;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.ParameterTool;

import net.sf.json.JSONObject;

//发动机信息类接口实现类
@Service("EngineMsgService")
public class EngineMsgServiceImpl implements EngineMsgService {

    private final static Logger log = Logger.getLogger(AuthServiceImpl.class);
    @Autowired
    private EngineMsgDao engineMsgDao;
    @Resource
    private WorkOrderTDao workOrderTDao;
    @Resource
    private CompanyTDao companyTDao;
    @Resource
    private MemberDao memberDao;
    @Resource
    private ServiceStationDao serviceStationDao;
    @Resource
    private UserTDao userTDao;
    @Autowired
    private DictionariesTDao dictionariesTDao;


    //发动机校验
    @Transactional
    @Override
    public ModelAndView engineMsgCheckOut(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String serviceChannel = MapUtils.getString(map, "serviceChannel");
        String ESN = MapUtils.getString(map, "ESN");
        //判断ESN号或服务渠道是否为空
        if (StringUtils.isEmpty(serviceChannel) || StringUtils.isEmpty(ESN)) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }

        try {
            CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().verifyEngineInfo(serviceChannel, ESN);
            if (cRMResponeEntity.getStatus() == 0) {
                // 只有DBU存在status为0并且data为空的情况
                if(cRMResponeEntity.getData().size() == 0){
                    Map<String,Object> data = new HashMap<>();
                    data.put("customerInfoList",getCustomerInfoList(ESN,serviceChannel));
                    ParameterTool.writeResponse(response, 2, "查无发动机信息",data);
                    return null;
                }

                //1.先根据发动机号ESN从发动机信息表EngineMsg中查询是否有数据
                EngineMsg engineMsg = engineMsgDao.getEngineMsgByESN(map);
                if (null != engineMsg) {
                    // 如果发动机信息表EngineMsg中查询到数据
                    // 1.经crm数据插入发动机信息表
                    Map<String,Object> engineMsgMap = new HashMap<>();
                    engineMsgMap.put("id", engineMsg.getId());
                    engineMsgMap.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo")!=null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                    engineMsgMap.put("vehicleCompany",(cRMResponeEntity.getData().get("vehicleCompany")!=null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                    engineMsgMap.put("engineType",(cRMResponeEntity.getData().get("engineType")!=null ? cRMResponeEntity.getData().get("engineType") : ""));
                    engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor")!=null ? cRMResponeEntity.getData().get("manufactor") : ""));
                    engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel")!=null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                    engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate")!=null ? cRMResponeEntity.getData().get("saleDate") : ""));
                    engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes")!=null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                    engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications")!=null ? cRMResponeEntity.getData().get("applications") : ""));
                    engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate")!=null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
                    engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate")!=null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                    engineMsgDao.updateEngineMsg(engineMsgMap);
                    // 2.重新读取发动机信息
                    engineMsg = engineMsgDao.getEngineMsgByESN(map);

                    Map<String,Object> data = new HashMap<>();
                    data.put("EngineMsgId", engineMsg.getId());
                    data.put("SMN", engineMsg.getSMN());
                    data.put("equipmentNo", engineMsg.getEquipmentNo());
                    data.put("vehicleCompany", engineMsg.getVehicleCompany());
                    data.put("engineType", engineMsg.getEngineType());
                    data.put("manufactor", engineMsg.getManufactor());
                    data.put("serviceChannel", engineMsg.getServiceChannel());
                    data.put("saleDate", engineMsg.getSaleDate());
                    data.put("marketType", engineMsg.getMarketType());
                    //工单显示小时数还是公里数
                    this.getAttribute(data,engineMsg);
                    data.put("application", engineMsg.getApplication());
                    data.put("warrantyStartDate", engineMsg.getWarrantyStartDate());
                    data.put("shoppingDate", engineMsg.getShoppingDate());
                    data.put("customerInfoList", getCustomerInfoList(ESN, serviceChannel));

                    data.put("warrantyStartDate", cRMResponeEntity.getData().get("warrantyStartDate") != null ? cRMResponeEntity.getData().get("warrantyStartDate") : "");
                    data.put("marketType", cRMResponeEntity.getData().get("marketTypes") != null ? cRMResponeEntity.getData().get("marketTypes") : "");
                    data.put("application", cRMResponeEntity.getData().get("applications") != null ? cRMResponeEntity.getData().get("applications") : "");
                    //--------设备号
                    data.put("equipmentModel", (cRMResponeEntity.getData().get("equipmentModel") != null ? cRMResponeEntity.getData().get("equipmentModel") : ""));
                    //--------主机厂
                    data.put("vehicleCompany", (cRMResponeEntity.getData().get("vehicleCompany") != null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                    //--------底盘号
                    data.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo") != null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                    //将发动机信息返给手机端
                    ParameterTool.writeSuccessResponse(response, data);
                } else {
                    //发动机信息表EngineMsg中没有查询到数据，就根据发动机号(ESN)和服务渠道serviceChannel调用CRM接口查询发动机数据
                    //保存发动机信息表
                    Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
                    engineMsgMap.put("ESN", map.get("ESN"));
                    engineMsgMap.put("SMN", (cRMResponeEntity.getData().get("SMN") != null ? cRMResponeEntity.getData().get("SMN") : ""));
                    engineMsgMap.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo") != null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                    engineMsgMap.put("vehicleCompany",(cRMResponeEntity.getData().get("vehicleCompany")!=null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                    engineMsgMap.put("engineType",(cRMResponeEntity.getData().get("engineType")!=null ? cRMResponeEntity.getData().get("engineType") : ""));
                    engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor")!=null ? cRMResponeEntity.getData().get("manufactor") : ""));
                    engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel")!=null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                    engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate")!=null ? cRMResponeEntity.getData().get("saleDate") : ""));
                    engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes")!=null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                    engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications")!=null ? cRMResponeEntity.getData().get("applications") : ""));
                    engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate")!=null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
                    engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate")!=null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                    engineMsgDao.insertEngineMsg(engineMsgMap);  //保存发动机信息

                    engineMsg = engineMsgDao.getEngineMsgByESN(map);

                    Map<String,Object> data = new HashMap<>();
                    data.put("EngineMsgId", MapUtils.getLongValue(engineMsgMap,"id"));
                    data.put("SMN", engineMsg.getSMN());
                    data.put("equipmentNo", engineMsg.getEquipmentNo());
                    data.put("vehicleCompany", engineMsg.getVehicleCompany());
                    data.put("engineType", engineMsg.getEngineType());
                    data.put("manufactor", engineMsg.getManufactor());
                    data.put("serviceChannel", engineMsg.getServiceChannel());
                    data.put("saleDate", engineMsg.getSaleDate());
                    data.put("marketType", engineMsg.getMarketType());
                    //工单显示小时数还是公里数
                    this.getAttribute(data,engineMsg);
                    data.put("application", engineMsg.getApplication());
                    data.put("warrantyStartDate", engineMsg.getWarrantyStartDate());
                    data.put("shoppingDate", engineMsg.getShoppingDate());
                    data.put("customerInfoList", getCustomerInfoList(ESN, serviceChannel));
                    data.put("shoppingDate", engineMsg.getShoppingDate());
                    //--------设备号
                    data.put("equipmentModel", (cRMResponeEntity.getData().get("equipmentModel") != null ? cRMResponeEntity.getData().get("equipmentModel") : ""));
                    //--------主机厂
                    data.put("vehicleCompany", (cRMResponeEntity.getData().get("vehicleCompany") != null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                    //--------底盘号
                    data.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo") != null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                    ParameterTool.writeSuccessResponse(response, data);
                }
            } else {
                log.error("CRM系统同步发动机信息到APP系统失败!状态:" + cRMResponeEntity.getStatus() + ",错误信息:" + cRMResponeEntity.getMessage());
                if (serviceChannel.equals("CCI")) {
                    Map<String,Object> data = new HashMap<>();
                    data.put("customerInfoList",getCustomerInfoList(ESN,serviceChannel));
                    ParameterTool.writeResponse(response, 2, "查无发动机信息",data);
                } else {
                    ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
                }
            }
        } catch (Exception e) {
            log.error("通过CRM获取发动机信息异常：" + e);
            if (serviceChannel.equals("CCI")) {
                Map<String,Object> data = new HashMap<>();
                data.put("customerInfoList",getCustomerInfoList(ESN,serviceChannel));
                ParameterTool.writeResponse(response, 2, "查无发动机信息",data);
            } else {
                ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
            }
        }
        return null;
    }
    //获取字典值 ，工单里面显示小数还是公里数
    public void getAttribute(Map<String,Object> data,EngineMsg engineMsg){
        if (StringUtils.isNotBlank(engineMsg.getMarketType())) {
            //获取 字典项里面其他的属性
            List<Map<String, Object>> listByDTableNameRequired = dictionariesTDao.getDictionariesListByDTableName("WorkOrderMarketTypeRequired");
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(listByDTableNameRequired)) {
                Map<Object, Object> requiredCollect = listByDTableNameRequired.stream().collect(Collectors.toMap(e1 -> e1.get("DValue"), e2 -> e2.get("Remark")));
                if (requiredCollect.containsKey(engineMsg.getMarketType())) {
                    if (StringUtils.isNotBlank(MapUtils.getString(requiredCollect,engineMsg.getMarketType()))) {
                        com.alibaba.fastjson.JSONObject remarkData = com.alibaba.fastjson.JSONObject.parseObject(MapUtils.getString(requiredCollect,engineMsg.getMarketType()));
                        data.put("Attribute",remarkData.getString("Attribute"));
                    }
                }
            }
        }
    }

    /**
     * 变速箱号 校验
     * @param map
     * @return
     * 原有接口为getEngineInfo  入参为 ESN参数，并传入amt值校验即可 ，
     * 将amt值传入ESN参数校验
     * ESN校验和AMT校验 返回的响应数据接口和字段一致
     *
     */
    @Transactional
    @Override
    public ModelAndView engineMsgCheckOutByAmt(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String serviceChannel = MapUtils.getString(map, "serviceChannel");
        String amtNo = MapUtils.getString(map, "amtNo");
        List<Map<String, Object>> customerInfoList = new ArrayList<>();
        //判断ESN号或服务渠道是否为空
        if (StringUtils.isEmpty(serviceChannel) || StringUtils.isEmpty(amtNo)) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }

        try {
            CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().verifyEngineInfo(serviceChannel, amtNo);
            if (cRMResponeEntity.getStatus() == 0) {
                // 只有DBU存在status为0并且data为空的情况
                if(cRMResponeEntity.getData().size() == 0){
                    Map<String,Object> data = new HashMap<>();
                    data.put("customerInfoList",getCustomerInfoListByAmt(amtNo,serviceChannel));
                    ParameterTool.writeResponse(response, 2, "查无变速箱信息",data);
                    return null;
                }
                /**
                 * DCEC amt工单需求
                 * 查询历史工单联系人和电话
                 */
                /**
                 *  1.先根据变速箱号 amtNo 从发动机信息表EngineMsg中查询是否有数据
                 */
                map.put("amtNo", cRMResponeEntity.getData().get("ESN") != null ? cRMResponeEntity.getData().get("ESN") : "");
                EngineMsg engineMsg = engineMsgDao.getEngineMsgByAmtNo(map);
                if (null != engineMsg) {
                    /**
                     * 如果发动机信息表EngineMsg中查询到数据
                     * 1.将crm数据插入发动机信息表
                     */
                    Map<String,Object> engineMsgMap = new HashMap<>();
                    engineMsgMap.put("id", engineMsg.getId());
                    engineMsgMap.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo")!=null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                    engineMsgMap.put("vehicleCompany",(cRMResponeEntity.getData().get("vehicleCompany")!=null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                    engineMsgMap.put("engineType",(cRMResponeEntity.getData().get("engineType")!=null ? cRMResponeEntity.getData().get("engineType") : ""));
                    engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor")!=null ? cRMResponeEntity.getData().get("manufactor") : ""));
                    engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel")!=null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                    engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate")!=null ? cRMResponeEntity.getData().get("saleDate") : ""));
                    engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes")!=null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                    engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications")!=null ? cRMResponeEntity.getData().get("applications") : ""));
                    engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate")!=null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
                    engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate")!=null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                    engineMsgMap.put("amtNo", (cRMResponeEntity.getData().get("ESN")!=null ? cRMResponeEntity.getData().get("ESN") : ""));
                    engineMsgDao.updateEngineMsg(engineMsgMap);
                    /**
                     * 2.重新读取变速箱信息
                     */
                    engineMsg = engineMsgDao.getEngineMsgByAmtNo(map);

                    Map<String,Object> data = new HashMap<>();
                    data.put("EngineMsgId", engineMsg.getId());
                    data.put("SMN",engineMsg.getSMN());
                    data.put("equipmentNo", engineMsg.getEquipmentNo());
                    data.put("vehicleCompany", engineMsg.getVehicleCompany());
                    data.put("engineType",engineMsg.getEngineType());
                    data.put("manufactor", engineMsg.getManufactor());
                    data.put("serviceChannel", engineMsg.getServiceChannel());
                    data.put("saleDate", engineMsg.getSaleDate());
                    data.put("marketType", engineMsg.getMarketType());
                    data.put("application", engineMsg.getApplication());
                    data.put("warrantyStartDate", engineMsg.getWarrantyStartDate());
                    data.put("shoppingDate", engineMsg.getShoppingDate());
                    data.put("amtNo", cRMResponeEntity.getData().get("ESN") != null ? cRMResponeEntity.getData().get("ESN") : "");

                    data.put("customerInfoList",getCustomerInfoListByAmt(amtNo,serviceChannel));

                    //将发动机信息返给手机端
                    ParameterTool.writeSuccessResponse(response, data);
                } else {
                    /**
                     * 发动机信息表EngineMsg中没有查询到数据，就根据变速箱号(amtNo)和服务渠道serviceChannel调用CRM接口查询变速箱数据
                     * 保存发动机信息表
                     */
                    Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
//                    engineMsgMap.put("ESN", map.get("ESN"));
                    engineMsgMap.put("ESN",  map.get("amtNo"));
                    engineMsgMap.put("amtNo", map.get("amtNo"));
                    engineMsgMap.put("SMN", cRMResponeEntity.getData().get("SMN"));
                    engineMsgMap.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo")!=null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                    engineMsgMap.put("vehicleCompany",(cRMResponeEntity.getData().get("vehicleCompany")!=null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                    engineMsgMap.put("engineType",(cRMResponeEntity.getData().get("engineType")!=null ? cRMResponeEntity.getData().get("engineType") : ""));
                    engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor")!=null ? cRMResponeEntity.getData().get("manufactor") : ""));
                    engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel")!=null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                    engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate")!=null ? cRMResponeEntity.getData().get("saleDate") : ""));
                    engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes")!=null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                    engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications")!=null ? cRMResponeEntity.getData().get("applications") : ""));
                    engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate")!=null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
                    engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate")!=null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                    /**
                     * 保存变速箱信息
                     */
                    engineMsgDao.insertEngineMsgByAmt(engineMsgMap);

                    engineMsg = engineMsgDao.getEngineMsgByAmtNo(map);

                    Map<String,Object> data = new HashMap<>();
                    data.put("EngineMsgId", MapUtils.getLongValue(engineMsgMap,"id"));
                    data.put("SMN",engineMsg.getSMN());
                    data.put("equipmentNo", engineMsg.getEquipmentNo());
                    data.put("vehicleCompany", engineMsg.getVehicleCompany());
                    data.put("engineType",engineMsg.getEngineType());
                    data.put("manufactor", engineMsg.getManufactor());
                    data.put("serviceChannel", engineMsg.getServiceChannel());
                    data.put("saleDate", engineMsg.getSaleDate());
                    data.put("marketType", engineMsg.getMarketType());
                    data.put("application", engineMsg.getApplication());
                    data.put("warrantyStartDate", engineMsg.getWarrantyStartDate());
                    data.put("shoppingDate",engineMsg.getShoppingDate());
                    data.put("amtNo",engineMsg.getAmtNo());
                    data.put("customerInfoList",getCustomerInfoListByAmt(amtNo,serviceChannel));
                    ParameterTool.writeSuccessResponse(response, data);
                }
            } else {
                log.error("CRM系统同步发动机信息到APP系统失败!状态:" + cRMResponeEntity.getStatus() + ",错误信息:" + cRMResponeEntity.getMessage());
                if (serviceChannel.equals("CCI")) {
                    Map<String,Object> data = new HashMap<>();
                    data.put("customerInfoList",getCustomerInfoListByAmt(amtNo,serviceChannel));
                    ParameterTool.writeResponse(response, 2, "查无变速箱信息",data);
                } else {
                    ParameterTool.writeResponse(response, 1, "变速箱号不存在,请联系400!");
                }
            }
        } catch (Exception e) {
            log.error("通过CRM获取发动机信息异常：" + e);
            if (serviceChannel.equals("CCI")) {
                Map<String,Object> data = new HashMap<>();
                data.put("customerInfoList",getCustomerInfoListByAmt(amtNo,serviceChannel));
                ParameterTool.writeResponse(response, 2, "查无变速箱信息",data);
            } else {
                ParameterTool.writeResponse(response, 1, "变速箱号不存在,请联系400!");
            }
        }
        return null;
    }


    //CCEC发动机校验
    @Transactional
    @Override
    public ModelAndView engineMsgCheckOutCCEC(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String serviceChannel = MapUtils.getString(map, "serviceChannel");
        String esn = MapUtils.getString(map, "ESN");
        //判断ESN号或服务渠道是否为空
        if (StringUtils.isEmpty(serviceChannel) || StringUtils.isEmpty(esn)) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }
        try {
            Map<String,Object> engineMsgMap = engineMsgDao.getSMNByESN(esn);
            JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
            Map<String,Object> returnMap = new HashMap<>();
            if(MapUtils.isNotEmpty(engineMsgMap)){
                if(StringUtils.isEmpty(MapUtils.getString(engineMsgMap,"SONo",""))){
                    ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
                }else{
                    returnMap.put("ESN",MapUtils.getString(engineMsgMap,"ESN",""));
                    returnMap.put("SMN",MapUtils.getString(engineMsgMap,"SMN",""));
                    returnMap.put("soNo",MapUtils.getString(engineMsgMap,"SONo",""));
                    returnMap.put("series",MapUtils.getString(engineMsgMap,"Series",""));
                    returnMap.put("isWarrantyStart",MapUtils.getIntValue(engineMsgMap,"ISWarrantyStart",2));
                    returnMap.put("engineType",MapUtils.getString(engineMsgMap,"engineType",""));
                    returnMap.put("warrantyStartDate",MapUtils.getString(engineMsgMap,"WarrantyStartDate",""));
                    returnMap.put("estimateWarrantyStartDate",MapUtils.getString(engineMsgMap,"EstimateWarrantyStartDate",""));
                    returnMap.put("EngineMsgId",MapUtils.getLongValue(engineMsgMap,"id"));
                    returnMap.put("engineProducedDate",MapUtils.getString(engineMsgMap,"EngineProducedDate",""));
                    returnMap.put("engineStartDatePicUrl",MapUtils.getString(engineMsgMap,"EngineStartDatePicUrl",""));
                    returnMap.put("customerInfoList",getCustomerInfoList(esn,serviceChannel));
                    obj.put("status", 0);
                    obj.put("msg", "success");
                    obj.put("data", returnMap);
                    ParameterTool.writeResponse(response, obj.toString());
                }
            }else{
                ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }


    private List<Map<String, Object>> getCustomerInfoList(String ESN, String serviceChannel) {
        List<Map<String, Object>> customerInfoList = new ArrayList<>();
        CompanyT companyT = companyTDao.getCompanyInfoByCompanyNo(serviceChannel);
        UserT userT = UserThreadLocal.get();
        long stataionId = 0;
        if (null != userT) {
            stataionId = userT.getServiceStationID();
        }
        if (null != companyT) {
            if ("CCEC".equals(serviceChannel)) {   //ccec渠道服务站站长创建服务工单    查询用户信息时只查询别渠道本服务站的用户历史信息  3.2.0运维需求
                List<Map<String, Object>> dataCustomerInfoList = workOrderTDao.getChannelCustomerInfoByESNStationId(ESN, companyT.getId(), stataionId);
                if (CollectionUtils.isNotEmpty(dataCustomerInfoList)) {
                    customerInfoList = dataCustomerInfoList;
                }
            } else {
                List<Map<String, Object>> dataCustomerInfoList = workOrderTDao.getChannelCustomerInfoByESN(ESN, companyT.getId());
                if (CollectionUtils.isNotEmpty(dataCustomerInfoList)) {
                    customerInfoList = dataCustomerInfoList;
                }
                if("DCEC".equals(serviceChannel)){    // jira:CDAP-3703  dcec芯管家跳转e康并创建服务工单，这里需要将上面查出来的数据，拼接上芯管家的数据并去重
                    Map<String,Object> serviceStationMap = serviceStationDao.getServiceStationById(stataionId);
                    String stationNo = MapUtils.getString(serviceStationMap,"StationNo","");
                    if(StringUtils.isNotEmpty(stationNo) && StringUtils.isNotEmpty(ESN)){
                        List<Map<String,Object>> userListMap = userTDao.getUserByEsnSSno(ESN,stationNo);
                        if(CollectionUtils.isNotEmpty(userListMap)){
                            customerInfoList.addAll(userListMap);
                        }
                        if(CollectionUtils.isNotEmpty(customerInfoList)){
                            customerInfoList = customerInfoList.stream().collect(
                                    Collectors.collectingAndThen(
                                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(customerInfo -> MapUtils.getString(customerInfo,"customerName","") + ";" + MapUtils.getString(customerInfo,"customerPhone","")))), ArrayList::new)
                            );
                        }
                    }


                }
            }

        }
        return customerInfoList;
    }

    public List<Map<String, Object>> getCustomerInfoListByAmt(String amtNo, String serviceChannel) {
        List<Map<String, Object>> customerInfoList = new ArrayList<>();
        CompanyT companyT = companyTDao.getCompanyInfoByCompanyNo(serviceChannel);
        UserT userT = UserThreadLocal.get();
        long stataionId = 0;
        if (null != userT) {
            stataionId = userT.getServiceStationID();
        }
        if (null != companyT) {
            /**
             * 查询用户信息时只查询别渠道本服务站的用户历史信息
             */
            if ("DCEC".equals(serviceChannel)) {
                List<Map<String, Object>> dataCustomerInfoList = workOrderTDao.getChannelCustomerInfoByAmtNoStationId(amtNo, companyT.getId(), stataionId);
                if (CollectionUtils.isNotEmpty(dataCustomerInfoList)) {
                    customerInfoList = dataCustomerInfoList;
                }
            }

        }
        return customerInfoList;
    }

    @Override
    public void validateEngine(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String serviceChannel = MapUtils.getString(map,"serviceChannel");
        String esn = MapUtils.getString(map,"ESN");
        if(StringUtils.isEmpty(esn) || StringUtils.isEmpty(serviceChannel)){
            ParameterTool.writeErrorResponse(response,-5);
            return;
        }

        // 查看各渠道是否有发动机信息
        Boolean dbuHasEngine = Boolean.TRUE;
        // 非CCEC逻辑，需要调用CRM
        if(!serviceChannel.equals("CCEC")){
            CRMResponeEntity responseEntity = CRMApiUtils.getCRMServiceApi().verifyEngineInfo(serviceChannel, esn);
            if(serviceChannel.equals("DCEC")){
                if(responseEntity.getStatus() != 0){
                    ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
                    return;
                }
            }else if(serviceChannel.equals("CCI")){
                if (responseEntity.getStatus() != 0 || responseEntity.getData().size() == 0) {
                    dbuHasEngine = Boolean.FALSE;
                }
            }else{
                if(responseEntity.getStatus() != 0){
                    ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
                    return;
                }
            }
        }


        //拼装本地数据
        Map<String,Object> engineMsg = engineMsgDao.getSMNByESN(esn);
        // CCEC渠道直接判断数据库
        if(serviceChannel.equals("CCEC")){
            if(MapUtils.isNotEmpty(engineMsg)){
                String soNo = MapUtils.getString(engineMsg,"SONo");
                if(StringUtils.isEmpty(soNo)){
                    ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
                    return;
                }
            }else{
                ParameterTool.writeResponse(response, 1, "发动机号不存在,请联系400!");
                return;
            }
        }

        if(null != engineMsg){
            Map<String,Object> data = new HashMap<>();
            data.put("EngineMsgId",MapUtils.getLong(engineMsg,"id"));
            data.put("ESN",MapUtils.getString(engineMsg,"ESN"));
            data.put("SMN",MapUtils.getString(engineMsg,"SMN",""));
            data.put("VIN",MapUtils.getString(engineMsg,"equipmentNo",""));
            data.put("OEMID",0L);
            data.put("OEMName",MapUtils.getString(engineMsg,"vehicleCompany",""));
            data.put("EngineType",MapUtils.getString(engineMsg,"EngineType",""));
            String warrantyStartDate = MapUtils.getString(engineMsg,"WarrantyStartDate","");
            data.put("WarrantyStartDate",warrantyStartDate);
            String application = MapUtils.getString(engineMsg,"Application","");
            data.put("Application",application);
            String marketType = MapUtils.getString(engineMsg,"MarketType","");
            data.put("MarketType",marketType);
            String shoppingDate = MapUtils.getString(engineMsg,"ShoppingDate","");
            data.put("ShoppingDate",shoppingDate);
            String soNo = MapUtils.getString(engineMsg,"SONo","");
            data.put("SONo",soNo);
            String series = MapUtils.getString(engineMsg,"Series","");
            data.put("Series",series);
            Integer isWarrantyStart = MapUtils.getInteger(engineMsg,"ISWarrantyStart",2);
            data.put("ISWarrantyStart",isWarrantyStart);
            String estimateWarrantyStartDate = MapUtils.getString(engineMsg,"EstimateWarrantyStartDate","");
            data.put("EstimateWarrantyStartDate",estimateWarrantyStartDate);
            String engineProducedDate = MapUtils.getString(engineMsg,"EngineProducedDate","");
            data.put("EngineProducedDate",engineProducedDate);

            //判断必填信息是否完整
            if(serviceChannel.equals("DCEC")){
                data.put("isCompleted",1);
            }else if(serviceChannel.equals("CCI")){
                if(StringUtils.isEmpty(warrantyStartDate) || StringUtils.isEmpty(application) || StringUtils.isEmpty(marketType)){
                    data.put("isCompleted",0);
                }else {
                    data.put("isCompleted",1);
                }
            }else{
                data.put("isCompleted",1);
            }
            if(dbuHasEngine){
                ParameterTool.writeSuccessResponse(response,data);
            }else{
                ParameterTool.writeResponse(response,2,"查无发动机信息",data);
            }
        }else{
            ParameterTool.writeResponse(response,3,"本地查无发动机信息");
        }
    }

    @Override
    public void getEngineMsgByESN(Map<String,Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String esn = MapUtils.getString(map,"ESN");
        if(StringUtils.isNotEmpty(esn)){
            EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
            if(null != engineMsg){
                Map<String,Object> data = new HashMap<>();
                data.put("ESN",engineMsg.getESN());
                data.put("SMN",engineMsg.getSMN());
                data.put("marketType",engineMsg.getMarketType());
                data.put("application",engineMsg.getApplication());
                ParameterTool.writeSuccessResponse(response,data);
            }else{
                ParameterTool.writeResponse(response,2,"查无发动机信息");
            }
        }else {
            ParameterTool.writeResponse(response,1,"ESN为空，无法查询");
        }
    }


    @Override
    public ModelAndView checkOutDYEngine(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String ESN = MapUtils.getString(map, "ESN");
        //判断ESN号是否为空
        if (StringUtils.isEmpty(ESN)) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }
        Map<String,Object> data = new HashMap<>();
        Map<String,Object> engineMap = engineMsgDao.getSMNByESN(ESN);
        int isDYESN = 0;  //是否是大运的发动机  (0:否   1:是)
        if(MapUtils.isNotEmpty(engineMap)){
            int oemFlag = MapUtils.getIntValue(engineMap,"OEMFlag",0);  //获取数据库中发动机是否是大运的标识
            if(oemFlag == 1){
                isDYESN = 1;
            }
            if(isDYESN == 1){
                //车牌号
                data.put("equipmentNo",MapUtils.getString(engineMap,"equipmentNo",""));
                //增加是否是大运会员标志
                int isDYMember = memberDao.getIsDYMemberByUserId(userT.getId());
                data.put("isDYMember",isDYMember);
            }
        }
        data.put("isDYESN",isDYESN);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    @Override
    public JSONObject getOEMInfoFromCrmXCEC() {
    	/**
    	 * 从crm获取主机厂、发动机系列、发动机用途信息
    	 */
    	CRMResponeEntity oemInfoFromCrmXCEC = CRMApiUtils.getCRMServiceApi().getOEMInfoFromCrmXCEC();

    	if(oemInfoFromCrmXCEC.getStatus() != 0) {
    		throw new RuntimeException(oemInfoFromCrmXCEC.getMessage());
    	}else {
    		return oemInfoFromCrmXCEC.getData();
    	}
    }

    private static JSONObject emptyJson = new JSONObject();

    @Override
    public JSONObject getOEMInfoFromCrmByEsnXCEC(String esn) {
    	/**
    	 * 根据esn从crm获取主机厂、发动机系列、发动机用途信息
    	 */
    	CRMResponeEntity oemInfoFromCrmXCEC = CRMApiUtils.getCRMServiceApi().getOEMInfoFromCrmByEsnXCEC(esn);

    	List<Map<String, Object>> infoList = getCustomerInfoList(esn, "XCEC");

    	log.info(String.format("esn:%s 对应的客户列表:%s", esn, infoList));

    	JSONObject obj = new JSONObject();

    	if(oemInfoFromCrmXCEC.getStatus() != 0) {
    		obj.put("esnInfo", emptyJson);
    	}else {
    		JSONObject data = oemInfoFromCrmXCEC.getData();
    		if(null == data || data.isEmpty()) {
    			obj.put("esnInfo", emptyJson);
    		}else {
    			obj.put("esnInfo", data);
    		}
    	}
    	if(CollectionUtils.isEmpty(infoList)) {
			obj.put("customers", Collections.EMPTY_LIST);
		}else {
			obj.put("customers", infoList);
		}
    	return obj;
    }
}
